package yf.mall.service.impl;

import yf.mall.common.Const;
import yf.mall.dao.MallActDao;
import yf.mall.dao.MallGoodsDao;
import yf.mall.dao.MallTypeDao;
import yf.mall.entity.*;
import com.yf.response.RRException;
import com.yf.service.impl.BaseServiceImpl;
import yf.mall.enums.*;
import yf.mall.service.MallOrderService;
import yf.mall.service.OrderItemService;
import yf.mall.vo.MallStoreVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import yf.mall.dao.MallStoreDao;
import yf.mall.service.MallStoreService;
import org.springframework.transaction.annotation.Transactional;
import yf.mall.vo.StoreTypeVo;

/**
 * 产品库存Service实现类
 *
 * @author hxf
 * @email 505860922@qq.com
 * @date Sun Sep 29 09:50:50 CST 2019
 */
@Service
public class MallStoreServiceImpl extends BaseServiceImpl<MallStoreEntity> implements MallStoreService {

    private MallStoreDao mallStoreDao;

    @Autowired
    private MallGoodsDao mallGoodsDao;

    @Autowired
    private MallOrderService orderService;

    @Autowired
    private OrderItemService itemService;


    @Autowired
    public void setDao(MallStoreDao mallStoreDao) {
        this.mallStoreDao = mallStoreDao;
        super.setBaseDao(mallStoreDao);
    }


//    @Override
//    public List<MallStoreVo> queryListVo(MallStoreVo mallStoreVo) {
//        return mallStoreDao.queryListVo(mallStoreVo);
//    }
//
//    @Override
//    public MallStoreVo getVo(Long id) {
//        return mallStoreDao.getVo(id);
//    }


    /**内部方法**/


    /**
     * 外部方法实现
     **/


    @Override
    @Transactional(rollbackFor = Exception.class)
    public MallStoreEntity increase(Long userId, Long goodsId, Integer quantity) {
        MallStoreEntity mallStoreEntity = mallStoreDao.findByUserIdAndGoodsId(userId, goodsId);
        if (mallStoreEntity == null) {
            mallStoreEntity = new MallStoreEntity(userId, goodsId, null, 0, 0);
            mallStoreDao.save(mallStoreEntity);
        }
        mallStoreEntity.setQuantity(mallStoreEntity.getQuantity() + quantity);
        //增加
        mallStoreDao.increase(userId, goodsId, quantity);
        return mallStoreEntity;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public MallStoreEntity decrease(Long userId, Long goodsId, Integer quantity) {
        MallStoreEntity mallStoreEntity = mallStoreDao.findByUserIdAndGoodsId(userId, goodsId);
        MallGoodsEntity mallGoodsEntity = mallGoodsDao.get(goodsId);
        if (mallStoreEntity == null) {
            mallStoreEntity = new MallStoreEntity(userId, goodsId, null, 0, 0);
            mallStoreDao.save(mallStoreEntity);
        }
        if (mallStoreEntity.getQuantity() - quantity < 0) {
            throw new RRException(mallGoodsEntity.getName() + "账户余额不足");
        }
        //减少 TODO 事务问题  会造成负数
        mallStoreDao.decrease(userId, goodsId, quantity);
        mallStoreEntity.setQuantity(mallStoreEntity.getQuantity() - quantity);
        return mallStoreEntity;
    }


    //后台发货的退回库存 相关的还货退回
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void backDelivery(String orderNo) {
        MallOrderEntity orderEntity = orderService.findByOrderNo(orderNo);
        //后台发货 商城发货的直接退钱了不用退货
        List<OrderItemEntity> items = itemService.findByOrderId(orderEntity.getId());
        items.forEach(item -> {
            mallStoreDao.increase(orderEntity.getUserId(), item.getGoodsId(), item.getQuantity());
        });
    }

/*    @Override
    @Transactional(rollbackFor = Exception.class)
    public void backCod(String orderNo) {
        //还货的
        List<MallOrderEntity> orderEntities = orderService.findReturn(orderNo);
        orderEntities.forEach(orderEntity1 -> {
            back(orderEntity1);
        });
    }*/

    /**
     * TODO 追回进货券
     *
     * @param orderNo
     */
/*    @Override
    @Transactional(rollbackFor = Exception.class)
    public void backAutoBuy(String orderNo) {
        //自动购买的
        List<MallOrderEntity> orderEntities = orderService.findAutoBuy(orderNo);
        orderEntities.forEach(orderEntity1 -> {

        });
    }*/

    //生成逆向退回订单
    private void back(MallOrderEntity orderEntity) {
        List<OrderItemEntity> items = itemService.findByOrderId(orderEntity.getId());
        orderEntity = orderService.buildBackOrder(orderEntity);
        orderService.save(orderEntity);
        for (OrderItemEntity item : items) {
            item.setId(null);
            item.setOrderId(orderEntity.getId());
            itemService.save(item);
            //库存退回
            if (!orderEntity.getUserId().equals(Const.ADMIN_ID)) {
                increase(orderEntity.getUserId(), item.getGoodsId(), item.getQuantity());
            }
            //库存减少
            if (!orderEntity.getFromUserId().equals(Const.ADMIN_ID)) {
                decrease(orderEntity.getUserId(), item.getGoodsId(), item.getQuantity());
            }
        }

    }
    @Autowired
    private MallActDao actDao;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void transfer(Long orderId) {
        MallOrderEntity orderEntity = orderService.get(orderId);
        List<OrderItemEntity> items = itemService.findByOrderId(orderId);

        items.forEach(item -> {
            MallGoodsEntity goodsEntity = mallGoodsDao.get(item.getGoodsId());
            //如果是活动产品 则需要扣活动库存 只限商城发货
            if(orderEntity.getOrderType() == MallOrderOrderTypeEnum.DELIVERY.getIndex() && orderEntity.getBusType() == MallOrderBusTypeEnum.BUY.getIndex()){
                MallActEntity actEntity = actDao.findByGoodsIdAndstatus(item.getGoodsId(), MallActStatusEnum.OPEN.getIndex());
                if (actEntity != null){
                    if (actEntity.getStock() != null && !actEntity.getStock().equals("")){
                        if (actEntity.getStock() >= item.getQuantity()){
                            actEntity.setStock(actEntity.getStock()-item.getQuantity());
                            actDao.update(actEntity);
                        }
                    }
                }
            }
            //如果是库存发货不是代理有利的产品 也要扣库存
            if ( (orderEntity.getOrderType() == MallOrderOrderTypeEnum.DELIVERY.getIndex() && orderEntity.getBusType() == MallOrderBusTypeEnum.SEND.getIndex()) ||
                    mallGoodsDao.get(item.getGoodsId()).getSaleType().equals(MallGoodsSaleTypeEnum.AGENT.getIndex())|| mallGoodsDao.get(item.getGoodsId()).getSaleType().equals(MallGoodsSaleTypeEnum.DAY_SEL.getIndex())) {
                //是代理有利的产品 如果是库存发货和还货需要走库存
                if (orderEntity.getBusType() == MallOrderBusTypeEnum.SEND.getIndex() || orderEntity.getBusType() ==MallOrderBusTypeEnum.RETURN.getIndex()){
                    decrease(orderEntity.getFromUserId(), item.getGoodsId(), item.getQuantity());
                }
                //如果是进货 是公司的产品也需要走库存
                if (orderEntity.getBusType() == MallOrderBusTypeEnum.BUY.getIndex() && (goodsEntity.getUserId()== null || goodsEntity.getUserId().equals(Const.ADMIN_ID))){
                    decrease(orderEntity.getFromUserId(), item.getGoodsId(), item.getQuantity());
                }
            } else {
                mallGoodsDao.decreaseSkuStock(item.getGoodsId(), item.getSkuName(), item.getQuantity());
            }
            //所有产品模式扣库存 21/01/18
            int stock = goodsEntity.getStock() - item.getQuantity();
            mallGoodsDao.decreaseStock(item.getGoodsId(), item.getQuantity());
            //如果不是公司产品并且库存为0 则自动下架
            if (stock <= 0 && goodsEntity.getUserId() != null && !goodsEntity.getUserId().equals(Const.ADMIN_ID)){
                goodsEntity.setShelf(MallGoodsShelfEnum.DOWN.getIndex());
                goodsEntity.setStock(0);
                mallGoodsDao.update(goodsEntity);
            }
            //转货订单 到账人要增加
            if (MallOrderOrderTypeEnum.TRANSFER.getIndex() == orderEntity.getOrderType()) {
                increase(orderEntity.getUserId(), item.getGoodsId(), item.getQuantity());
            }
        });
    }

    @Override
    public List<MallStoreVo> findByUserId(Long userId) {
        return mallStoreDao.findByUserId(userId);
    }

    @Autowired
    private MallTypeDao mallTypeDao;

    /**
     * que
     * 新的发货转货库存列表
     *
     * @param userId
     * @return
     */
    @Override
    public List<StoreTypeVo> storeType(Long userId) {
        List<StoreTypeVo> storeTypeVOS = new ArrayList<>(); //存储结果集
        List<MallStoreVo> storeVoList = mallStoreDao.findByUserId(userId); //获取库存
        boolean temp = true;
        if (storeVoList != null && storeVoList.size() > 0) {
            for (MallStoreVo mallStoreVo : storeVoList) {
                //库存数量小于1 不添加
                if (mallStoreVo.getStore().getQuantity() < 1) {
                    continue;
                }
                //二级分类
                List<Long> types = mallTypeDao.findByGoodsId(mallStoreVo.getGoods().getId());
                //根据二级分类获取一级分类
                if (types != null && types.size() > 0) {
                    for (Long type : types) {
                        MallTypeEntity mallTypeEntity = mallTypeDao.get(type);
                        if (mallTypeEntity != null) {
                            //获取一级分类
                            MallTypeEntity oneType = mallTypeDao.get(mallTypeEntity.getPid());

                            List<MallStoreVo> mallStoreTemp = new ArrayList<>(); //临时VO
                            //存储产品
                            mallStoreTemp.add(mallStoreVo);
                            StoreTypeVo sto = new StoreTypeVo();
                            //存储分类
                            sto.setMallTypeEntity(oneType);
                            sto.setMallStoreVos(mallStoreTemp);
                            //第一次循环直接添加
                            if (storeTypeVOS == null || storeTypeVOS.size() == 0) {
                                storeTypeVOS.add(sto);
                                continue;
                            }
                            //判断是否包含分类
                            if (storeTypeVOS != null && storeTypeVOS.size() > 0) {
                                boolean flag = containsType(storeTypeVOS, mallStoreVo, oneType);
                                //不包含 添加
                                if (!flag) {
                                    storeTypeVOS.add(sto);
                                }
                            }
                        }
                    }
                }
                if (types == null || types.size() == 0) {
                    //没有分类 new一个分类其他 存储
                    if (temp) {
                        MallTypeEntity mallType = new MallTypeEntity();
                        mallType.setName("其他");
                        mallType.setId(9999L);
                        mallType.setSort(99);
                        List<MallStoreVo> MallStoreTemp = new ArrayList<>(); //临时VO
                        //存储产品
                        MallStoreTemp.add(mallStoreVo);
                        StoreTypeVo sto = new StoreTypeVo();
                        //存储分类
                        sto.setMallTypeEntity(mallType);
                        sto.setMallStoreVos(MallStoreTemp);
                        storeTypeVOS.add(sto);
                        temp = false;
                    } else {
                        //不是第一次 获取其他分类添加
                        for (StoreTypeVo storeTypeVO : storeTypeVOS) {
                            if (storeTypeVO.getMallTypeEntity().getId().equals(9999L)) {
                                storeTypeVO.getMallStoreVos().add(mallStoreVo);
                            }
                        }
                    }
                }
            }
        }
        Collections.sort(storeTypeVOS, (s1, s2) -> {
            if (s1.getMallTypeEntity().getSort() != null && s2.getMallTypeEntity().getSort() != null) {
                if (s1.getMallTypeEntity().getSort() > s2.getMallTypeEntity().getSort()) {
                    return 1;
                }
            }
            return -1;
        });
        return storeTypeVOS;
    }

    //判断是否包含分类
    private boolean containsType(List<StoreTypeVo> storeTypeVOS, MallStoreVo mallStoreVo, MallTypeEntity oneType) {
        for (StoreTypeVo storeTypeVO : storeTypeVOS) {
            //存在分类
            if (storeTypeVO.getMallTypeEntity().getId().equals(oneType.getId())) {
                storeTypeVO.getMallStoreVos().add(mallStoreVo);
                return true;
            }
        }
        return false;
    }
}
